package com.xique.park.controller.mini;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.xique.common.core.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: caogq
 * @Date: 2022/8/3 11:58
 * @Description:
 */
@RestController
@RequestMapping("alipay")
@Slf4j
public class AlipayParkController {

    @Value("${alipay.h5.appid}")
    private String appid;

    @Value("${alipay.h5.appPublicKey}")
    private String appPublicKey;

    @Value("${alipay.h5.appPrivateKey}")
    private String appPrivateKey;

    @GetMapping("/getUserId")
    public AjaxResult getUserId(String authCode) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appid, appPrivateKey, "json", "UTF-8", appPublicKey, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            log.info("获取支付宝authCode：{}，后端返回userId: {}",authCode,oauthTokenResponse.getUserId());
            return oauthTokenResponse.getUserId() != null ? AjaxResult.success().put("userId", oauthTokenResponse.getUserId()) : AjaxResult.error("获取用户信息失败，请重试或者联系管理员！");
        } catch (AlipayApiException e) {
            //处理异常
            e.printStackTrace();
            return AjaxResult.error("获取用户信息失败，请重试或者联系管理员！");
        }
    }
}
